<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实体变更详情</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <style>
        .field-change-row {
            border-bottom: 1px solid #eee;
            padding: 8px 0;
        }
        .field-name {
            font-weight: bold;
            color: #007bff;
        }
        .old-value {
            text-decoration: line-through;
            color: #dc3545;
        }
        .new-value {
            color: #28a745;
            font-weight: bold;
        }
        .added-field {
            background-color: #d4edda;
        }
        .removed-field {
            background-color: #f8d7da;
        }
        .changed-field {
            background-color: #fff3cd;
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <h2>实体变更详情</h2>
        
        <div class="card mb-4">
            <div class="card-header">
                <h5>变更记录信息</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <table class="table table-sm">
                            <tr>
                                <td><strong>操作时间:</strong></td>
                                <td id="createTime"></td>
                            </tr>
                            <tr>
                                <td><strong>操作用户:</strong></td>
                                <td id="username"></td>
                            </tr>
                            <tr>
                                <td><strong>实体类名:</strong></td>
                                <td id="entityClass"></td>
                            </tr>
                            <tr>
                                <td><strong>实体ID:</strong></td>
                                <td id="entityId"></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <table class="table table-sm">
                            <tr>
                                <td><strong>操作类型:</strong></td>
                                <td id="operationType"></td>
                            </tr>
                            <tr>
                                <td><strong>操作描述:</strong></td>
                                <td id="operation"></td>
                            </tr>
                            <tr>
                                <td><strong>请求方法:</strong></td>
                                <td id="method"></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h5>字段变更详情</h5>
            </div>
            <div class="card-body">
                <div id="fieldChangesContainer">
                    <p class="text-muted">加载中...</p>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script>
        // 获取URL参数
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(window.location.href);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
        }
        
        // 加载实体变更详情
        function loadEntityChangeDetail() {
            const logId = getUrlParameter('id');
            if (!logId) {
                $('#fieldChangesContainer').html('<p class="text-danger">缺少日志ID参数</p>');
                return;
            }
            
            $.get('/sys/entityChangeLog/info?id=' + logId)
                .done(function(response) {
                    if (response.code !== 0) {
                        $('#fieldChangesContainer').html('<p class="text-danger">加载失败: ' + response.msg + '</p>');
                        return;
                    }
                    
                    const data = response.data;
                    
                    // 填充基本信息
                    $('#createTime').text(data.createDate || '');
                    $('#username').text(data.username || '');
                    $('#entityClass').text(getSimpleClassName(data.entityClass) || '');
                    $('#entityId').text(data.entityId || '');
                    $('#operationType').text(formatOperationType(data.operationType) || '');
                    $('#operation').text(data.operation || '');
                    $('#method').text(data.method || '');
                    
                    // 显示字段变更详情
                    renderFieldChanges(data);
                })
                .fail(function(xhr) {
                    $('#fieldChangesContainer').html('<p class="text-danger">加载失败: ' + xhr.responseText + '</p>');
                });
        }
        
        // 渲染字段变更详情
        function renderFieldChanges(data) {
            const container = $('#fieldChangesContainer');
            
            // 优先使用详细的字段变更信息（包含字段描述）
            if (data.detailedFieldChanges && data.detailedFieldChanges.length > 0) {
                renderDetailedFieldChanges(data.detailedFieldChanges);
                return;
            }
            
            // 如果有fieldChanges字段，直接使用
            if (data.fieldChanges && Object.keys(data.fieldChanges).length > 0) {
                renderFieldChangesFromMap(data.fieldChanges);
                return;
            }
            
            // 否则从beforeData和afterData生成
            if (data.beforeData || data.afterData) {
                generateAndRenderFieldChanges(data.beforeData, data.afterData);
                return;
            }
            
            container.html('<p class="text-muted">无字段变更信息</p>');
        }
        
        // 渲染详细字段变更（包含字段描述）
        function renderDetailedFieldChanges(detailedFieldChanges) {
            const container = $('#fieldChangesContainer');
            
            if (!detailedFieldChanges || detailedFieldChanges.length === 0) {
                container.html('<p class="text-muted">无字段变更信息</p>');
                return;
            }
            
            let html = '<div class="container-fluid">';
            
            // 遍历所有变更的字段
            detailedFieldChanges.forEach(change => {
                const fieldName = change.fieldName || '';
                const fieldDescription = change.fieldDescription || fieldName;
                const oldValue = change.oldValue;
                const newValue = change.newValue;
                
                let rowClass = '';
                let changeType = '';
                
                if (oldValue === null && newValue !== null) {
                    rowClass = 'added-field';
                    changeType = '新增';
                } else if (oldValue !== null && newValue === null) {
                    rowClass = 'removed-field';
                    changeType = '删除';
                } else if (oldValue !== newValue) {
                    rowClass = 'changed-field';
                    changeType = '修改';
                } else {
                    // 值没有变化
                    changeType = '无变化';
                }
                
                html += `
                    <div class="field-change-row ${rowClass}">
                        <div class="row">
                            <div class="col-md-3 field-name">${fieldName}</div>
                            <div class="col-md-2">${changeType}</div>
                            <div class="col-md-3 old-value">${formatValue(oldValue)}</div>
                            <div class="col-md-1 text-center">→</div>
                            <div class="col-md-3 new-value">${formatValue(newValue)}</div>
                        </div>
                        <div class="row mt-1">
                            <div class="col-md-3 text-muted"><small>${fieldDescription}</small></div>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            container.html(html);
        }
        
        // 从fieldChanges字段渲染
        function renderFieldChangesFromMap(fieldChanges) {
            const container = $('#fieldChangesContainer');
            
            if (!fieldChanges || Object.keys(fieldChanges).length === 0) {
                container.html('<p class="text-muted">无字段变更信息</p>');
                return;
            }
            
            let html = '<div class="container-fluid">';
            
            // 遍历所有变更的字段
            for (const fieldName in fieldChanges) {
                const change = fieldChanges[fieldName];
                const oldValue = change[0];
                const newValue = change[1];
                
                let rowClass = '';
                let changeType = '';
                
                if (oldValue === null && newValue !== null) {
                    rowClass = 'added-field';
                    changeType = '新增';
                } else if (oldValue !== null && newValue === null) {
                    rowClass = 'removed-field';
                    changeType = '删除';
                } else {
                    rowClass = 'changed-field';
                    changeType = '修改';
                }
                
                html += `
                    <div class="field-change-row ${rowClass}">
                        <div class="row">
                            <div class="col-md-3 field-name">${fieldName}</div>
                            <div class="col-md-2">${changeType}</div>
                            <div class="col-md-3 old-value">${formatValue(oldValue)}</div>
                            <div class="col-md-1 text-center">→</div>
                            <div class="col-md-3 new-value">${formatValue(newValue)}</div>
                        </div>
                    </div>
                `;
            }
            
            html += '</div>';
            container.html(html);
        }
        
        // 从beforeData和afterData生成并渲染字段变更
        function generateAndRenderFieldChanges(beforeData, afterData) {
            const container = $('#fieldChangesContainer');
            
            try {
                const beforeObj = beforeData ? JSON.parse(beforeData) : {};
                const afterObj = afterData ? JSON.parse(afterData) : {};
                
                const changes = {};
                
                // 处理修改后的字段
                for (const key in afterObj) {
                    const newValue = afterObj[key];
                    const oldValue = beforeObj[key];
                    
                    if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {
                        changes[key] = [oldValue, newValue];
                    }
                }
                
                // 处理删除的字段
                for (const key in beforeObj) {
                    if (!(key in afterObj)) {
                        changes[key] = [beforeObj[key], null];
                    }
                }
                
                renderFieldChangesFromMap(changes);
            } catch (e) {
                container.html('<p class="text-danger">解析数据失败: ' + e.message + '</p>');
            }
        }
        
        // 格式化值显示
        function formatValue(value) {
            if (value === null || value === undefined) {
                return '<span class="text-muted">(空)</span>';
            }
            
            if (typeof value === 'object') {
                return JSON.stringify(value, null, 2);
            }
            
            if (typeof value === 'string' && value.length > 100) {
                return value.substring(0, 100) + '...';
            }
            
            return value.toString();
        }
        
        // 获取简化的类名
        function getSimpleClassName(fullClassName) {
            if (!fullClassName) return '';
            return fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
        }
        
        // 格式化操作类型
        function formatOperationType(operationType) {
            const typeMap = {
                'INSERT': '新增',
                'UPDATE': '修改',
                'DELETE': '删除',
                'SELECT': '查询'
            };
            return typeMap[operationType] || operationType;
        }
        
        // 页面加载完成后加载数据
        $(document).ready(function() {
            loadEntityChangeDetail();
        });
    </script>
</body>
</html>